package com.rzx.mybackend.service.Impl;

import com.rzx.mybackend.dto.UserRegisterDTO;
import com.rzx.mybackend.entity.Role;
import com.rzx.mybackend.entity.User;
import com.rzx.mybackend.entity.UserRoleRel;
import com.rzx.mybackend.mapper.RoleMapper;
import com.rzx.mybackend.mapper.RoleUserRelMapper;
import com.rzx.mybackend.mapper.UserMapper;
import com.rzx.mybackend.mapstruct.MapStructMapper;
import com.rzx.mybackend.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * UserServiceImpl
 *
 * @author renzhexian
 * @date 2025/7/16
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final RoleMapper roleMapper;

    private final UserMapper userMapper;

    private final RoleUserRelMapper roleUserRelMapper;

    /*
    根据用户名获取用户角色信息
     */
    @Override
    public String getRoleByUserName(String userName) {

        return roleMapper.selectByUserUserName(userName);
    }

    /*
    新用户注册
     */
    @Transactional
    @Override
    public void register(UserRegisterDTO userRegisterDTO) {

        User user = MapStructMapper.INSTANCE.mapToUser(userRegisterDTO);

        Role role = MapStructMapper.INSTANCE.mapToRole(userRegisterDTO);

        // 检查用户名是否已存在

        userMapper.insert(user);

        roleUserRelMapper.insert(UserRoleRel.builder()
                .roleId(2L)
                .userId(user.getUserId())
                .build());

    }

    /*
    查询注册的用户名是否存在
     */
    @Override
    public int selectUserNameByUserName(String userName) {

        return userMapper.selectUserNameByUserName(userName);
    }

    /*
    根据用户名查询用户ID
     */
    @Override
    public Long selectUserIdByUserName(String userName) {

        return userMapper.selectUserDetails(User.builder()
                .userName(userName)
                .build()).getUserId();
    }

    @Override
    public User selectAllByUserId(Long userId) {

        return userMapper.selectAllByUserId(userId);
    }
}
